package com.huan.hadoop.mr;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
import org.apache.hadoop.mapreduce.lib.db.DBInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

/**
 * 从数据库中读取数据并写入都文件中，不经过reduce阶段
 *
 * @author huan.fu
 * @date 2023/7/16 - 10:32
 */
public class ReadDbDriver extends Configured implements Tool {

    public static void main(String[] args) throws Exception {
        // 构建配置对象
        Configuration configuration = new Configuration();
        // 配置当前作业需要的JDBC密码
        DBConfiguration.configureDB(
                configuration,
                "com.mysql.cj.jdbc.Driver",
                "jdbc:mysql://localhost:3306/temp_work",
                "root",
                "root@1993"
        );

        // 使用 ToolRunner 提交程序
        int status = ToolRunner.run(configuration, new ReadDbDriver(), args);
        // 退出程序
        System.exit(status);
    }

    @Override
    public int run(String[] args) throws Exception {
        // 构建Job对象实例 参数（配置对象，Job对象名称）
        Job job = Job.getInstance(getConf(), ReadDbDriver.class.getName());
        // 设置mr程序运行的主类
        job.setJarByClass(ReadDbDriver.class);
        // 设置mr程序运行的 mapper类型和reduce类型
        job.setMapperClass(ReadDbMapper.class);
        // 指定输出的类型
        job.setOutputKeyClass(NullWritable.class);
        job.setOutputValueClass(Text.class);

        // 此处不需要reduce task 设置为 0
        job.setNumReduceTasks(0);
        // 设置数据输入组件
        job.setInputFormatClass(DBInputFormat.class);
        DBInputFormat.setInput(job, Student.class,
                "select * from student",
                "select count(*) from student");
        // 设置数据输出组件
        FileOutputFormat.setOutputPath(job, new Path("/tmp/mr-read-from-db"));

        return job.waitForCompletion(true) ? 0 : 1;
    }
}
